package com.jieao.template.config.shiroConfig;

import com.jieao.template.entity.accountMgr.AccountDO;
import com.jieao.template.service.AccountService;
import com.jieao.template.service.PermissionService;
import com.jieao.template.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.List;

/**
 * @author 姜兆伟
 * @className AdminRealm
 * @date 2019-08-20 20:47
 */
public class CustomRealm extends AuthorizingRealm
{


    @Autowired
    @Lazy
    private AccountService accountService;

    @Autowired
    @Lazy
    private RoleService roleService;

    @Autowired
    @Lazy
    private PermissionService permissionService;

    /**
     * 进行权限校验的时候会调用
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)
    {
        List<String> stringRoleList = roleService.getAllRolesByUserId();
        List<String> stringPermissionList = permissionService.getAllPermissionByUserId();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(stringRoleList);
        simpleAuthorizationInfo.addStringPermissions(stringPermissionList);
        return simpleAuthorizationInfo;
    }

    /**
     * 用户登录的时候会调用
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException
    {
        System.out.println("认证 Admin doGetAuthenticationInfo");
        //从token获取用户信息，token代表用户输入
        String username = (String) token.getPrincipal();
        AccountDO user = accountService.queryByName(username);
        if (user == null)
        {
            return null;
        }
        //取密码
        String pwd = user.getEncryptedPassword();
        if (StringUtils.isBlank(pwd))
        {
            return null;
        }
        return new SimpleAuthenticationInfo(user, pwd, ByteSource.Util.bytes(user.getSalt()), getClass().getName());
    }

}
